package com.htfyun.eink.pw.core.ctrl;

import android.util.Log;

import androidx.annotation.NonNull;

import com.htfyun.eink.pw.core.EinkPWCoreControllerDummy;
import com.htfyun.eink.pw.core.IEinkPWCoreController;

import java.lang.reflect.Constructor;
import java.util.concurrent.atomic.AtomicReference;

public class PWCoreFactoryHelper {
    private static final String TAG = PWCoreFactoryHelper.class.getSimpleName();

    private static final AtomicReference<IEinkPWCoreController> sCachedControllerRef = new AtomicReference<>();

    private final static String CLS_IMPL = "com.htfyun.eink.pw.core.EinkPWCoreController";

    @NonNull
    public static IEinkPWCoreController getPWCoreController() {
        IEinkPWCoreController controller = sCachedControllerRef.get();
        if (controller != null) {
            return controller;
        }
        controller = createPWCoreController();
        sCachedControllerRef.set(controller);
        return controller;
    }

    @NonNull
    private static IEinkPWCoreController createPWCoreController() {
        try {
            Class<?> optClass = Class.forName(CLS_IMPL);
            Constructor<?> constructor = optClass.getConstructor();
            return (IEinkPWCoreController) constructor.newInstance();
        } catch (Exception e) {
            Log.e(TAG, "createPWCoreController: failed with Exception!!", e);
            e.printStackTrace();
        }
        return new EinkPWCoreControllerDummy();
    }
}
